# -*- coding: utf-8 -*-
from apscheduler.schedulers.blocking import BlockingScheduler
import time
import tushare as ts
import pymongo
from mongo_config import *

mongo_client = pymongo.MongoClient(MONGO_URL, 27017)
mongo_client_test = pymongo.MongoClient(MONGO_URL_TEST, 27017)
db = mongo_client_test[MONGO_DB_RES]

def parser_data(res, score):
    time_id = int(time.time())
    keys = score.keys()
    data_all = []
    for index, datum in res.iterrows():
        dicts = {}
        dicts['_id'] = datum['code']
        dicts['name'] = datum['name']
        dicts['time'] = time_id
        dicts['changepercent'] = datum['changepercent']
        dicts['trade'] = datum['trade']
        dicts['open'] = datum['open']
        dicts['high'] = datum['high']
        dicts['low'] = datum['low']
        dicts['pre_close'] = datum['settlement']
        if datum['settlement'] != 0:
            dicts['change_price'] = datum['trade'] - datum['settlement']
            if dicts['change_price'] < 0:
                dicts['change_range'] = '%.2f%%' % (-(datum['high'] - datum['low']) / datum['settlement'] * 100)
            else:
                dicts['change_range'] = '%.2f%%' % (-(datum['high'] - datum['low']) / datum['settlement'] * 100)
        else:
            dicts['change_price'] = 0
            dicts['change_range'] = 0
        dicts['volume'] = datum['volume']
        dicts['turnoverratio'] = datum['turnoverratio']
        dicts['amount'] = datum['amount']
        dicts['per'] = datum['per']
        dicts['pb'] = datum['pb']
        dicts['mktcap'] = datum['mktcap']
        dicts['nmc'] = datum['nmc']
        if datum['code'] in keys:
            dicts['max'] = score[datum['code']]
        else:
            dicts['max'] = 0
        data_all.append(dicts)
    return data_all


# 获取原数据、处理name、res
def select_data():
    src_db = mongo_client[SRC_MONGO_DB]
    collection_name = src_db['gube']
    dicts = {}
    collection_data = collection_name.find()
    for collection_datum in collection_data:
        code = collection_datum['_id']
        res = handle_res(collection_datum['res'])
        dicts[code] = res
    return dicts


# 处理res
def handle_res(res_list):
    max_val = 0
    values = [i for i in map(abs, res_list)]
    max_res = max(values)
    if max_res in res_list:
        max_val = max_res
    else:
        max_val = -max_res
    return max_val


def save_to_mongo(data_list):
    print(data_list)
    coll = db['details']
    coll.remove()
    try:
        coll.insert_many(data_list, ordered=False)
        print('insert ok!')
    except Exception as e:
        print(e)

# 处理股票详细数据
def main_today_all():
    res = ts.get_today_all()
    score = select_data()
    result = parser_data(res, score)
    save_to_mongo(result)


# if __name__ == '__main__':
#     main_today_all()
#     # 定义BlockingScheduler
#     sched = BlockingScheduler()
#     sched.add_job(main_today_all, 'interval', minutes=5)
#     sched.start()